package com.pi.nbcenter.device.task;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.pi.base.enumerate.redis.RedisCacheEnum;
import com.pi.base.util.cache.RedisUtil;
import com.pi.nbcenter.device.service.partner.BasePartnerSubscriptionService;

/**
 *  @description  每30秒统计设备是否有报警和
 *  
 * 
 * */
@Component
public class IotDeviceAlarmStatistic {
  
  private static final Logger logger = LoggerFactory.getLogger(IotDeviceAlarmStatistic.class);
  @Autowired
  private BasePartnerSubscriptionService partnerSubscriptionService;
  private static Pattern p = Pattern.compile("IOT_SERVERSIDE_ALARM_([A-Za-z0-9\\-]+)_(\\d)");
  
  @Scheduled(cron = "*/30 * * * * ?")
  public void sessionSyncronize(){
    try {
      Set<String> keys = RedisUtil.getKeys("IOT_SERVERSIDE_ALARM*");
      if(null != keys && !keys.isEmpty()) {
        for(String key: keys) {
          Matcher matcher = p.matcher(key);
          if(matcher.find()) {
            Object[] param = new Object[] {matcher.group(1), matcher.group(2)};
            String cachedStartTime = RedisUtil.get(RedisCacheEnum.IOT_SERVERSIDE_ALARM, param);
            logger.info("查询到锁具待报警缓存： {}", key);
            partnerSubscriptionService.sendUnlockAlarmIfNecessary(matcher.group(1), cachedStartTime, param);
          }
        }
      }
    } catch (Exception e) {
      logger.error("同步设备状态失败",e);
    }
  }
}
